const config = require("./config")
const app = getApp();
const fun = (options, doNotShowLoading) => {
  if (!doNotShowLoading) {
    wx.showLoading({
      title: '加载中',
    })
  }
  var header = options.header || {
  };
  if (!options.notVerifyAuthorization) {
    header['X-Access-Token'] = app.globalData.token;
  }
  return new Promise((resolve, reject) => {
    let url = `${config.serverUrl}${options.url}`;
    wx.request({
      url: url,
      data: options.data || {},
      header: header,
      method: options.method || 'GET',
      complete: res => {
        if (!doNotShowLoading) {
          wx.hideLoading();
        }
      },
      success: res => {
        let {
          statusCode,
          data
        } = res;
        if(statusCode === 200){
          resolve(res);
        }else if(statusCode === 401){
          wx.redirectTo({
            url: '/pages/login/login',
          })
        }else{
          console.error("请求失败", url, options.data, data)
          wx.showToast({
            title: `失败, ${data.message}`,
            icon: 'error'
          })
        }
      },
      fail: reject
    })
  })
}
export default fun